<template>
  <div class="directive-box">
    <div class="title-line list-caption mt15 ml10 relative">
      反馈模版
      <div class="title-oper">
        <IconButton
          :icon="visible.feedbackTemplate ? 'fold' : 'unfold'"
          :title="visible.feedbackTemplate ? '收起' : '展开'"
          :activated="false"
          @click.native="handleModuleToggle('feedbackTemplate')"
        ></IconButton>
      </div>
    </div>
    <div class="split-line mt18 mb18"></div>

    <div class="mt24 f14" ref="feedbackTemplate_ref">
      <span class="ml40">选择模版：</span>
      <div>
        <RadioGroup v-model="formData.template" @on-change="handleFeedbackTemplateChange">
          <Radio v-for="(fb, i) of templateOptions" class="ml40 mt12" :key="i" :label="fb.key" :disabled="fb.disabled">
            {{ fb.value }}
          </Radio>
        </RadioGroup>
      </div>
      <div class="ml20 d-inline-block mt20 mb4">{{ currItem.value || '稿件转发指令模版' }}：</div>
      <CommonTablePage
        class="mt10"
        height="auto"
        :columns="feedbackTemplate_columns"
        :tableData="tableData"
        :hide-page="true"
      ></CommonTablePage>
    </div>
  </div>
</template>

<script>
// request
import { getFeedbackTemplates } from '@/api/common/IssueDirective/index.js'
// components
import CommonTablePage from '@/components/common/CommonTablePage/CommonTablePage'
// utils
import { createCommonPage } from '/src/utils/service.js'
// service
// import { createFeedbackTemplate } from './service'
// import { feedbackTemplateMap } from './tableColumns'
export default {
  name: 'FeedbackTemplate',

  components: { CommonTablePage },

  props: {
    viewDetails: Object,
    currentDirectiveType: {
      default() {
        return {}
      },
    },
  },

  data: () => ({
    formData: {
      template: '', // 反馈模板ID
      ...createCommonPage(),
    },
    allTemplate: [],
    templateOptions: [],
    disabled: false,
    currItem: {},
    tableData: [{}],

    visible: {
      feedbackTemplate: true,
    },

    requetNum: 0, // viewDetails 监听更改 template 时， templateOptions未获取到数据的问题，解决两个都是异步的问题
  }),

  computed: {
    from() {
      return this.$route.query.f
    },

    feedbackTemplate_columns() {
      const curr = this.allTemplate.find((it) => it.name.key === this.currItem.key)
      if (!curr) return []
      const columns = this.getColumns(curr.columns)
      return columns
    },
  },

  watch: {
    templateOptions(v) {
      if (!v.length) return

      /* 从稿池 下发指令进入，禁用其它模板 */
      if (this.from === 'issue') {
        // console.log('templateOptions', this.currentDirectiveType)
        /* 没有key自己设置一个，不然其它选项无法禁用 */
        if (!this.currentDirectiveType.key) {
          this.$set(this.currentDirectiveType, 'key', 'ARTICLE')
        }
        this.$set(this.currentDirectiveType, 'custom', '随便设置一个数据，触发 watch')
      }

      /* 详情表格不需要默认值 禁用单选 */
      if (this.viewDetails.isDetails) {
        v.forEach((it) => (it.disabled = true))
        this.setRequetNum()
        return
      }
      this.formData.template = v.at(0).key
      this.handleFeedbackTemplateChange(this.formData.template)
    },

    /* 进行深度监听
    从稿池进入下发指令时，当模板数据获取到进行更换
    */
    currentDirectiveType: {
      handler(v) {
        // console.log('currentDirectiveType', v)
        const tm = this.allTemplate.find((it) => it.type.key === v.key)
        if (!tm) {
          this.templateOptionsDisable(false)
          return
        }

        const name_key = tm.name.key
        this.templateOptionsDisable(true, tm.type.key === 'OTHER', tm.name.key)
        this.formData.template = name_key
        this.handleFeedbackTemplateChange(this.formData.template)
        // this.disabled = true
      },
      deep: true,
    },

    viewDetails: {
      handler(v) {
        if (!v.isDetails) return
        this.setRequetNum()
      },
      deep: true,
    },
  },

  methods: {
    handleModuleToggle(module) {
      this.$parent.moduleHeightToggle(this, module)
    },

    setRequetNum() {
      this.requetNum++

      if (this.requetNum >= 2) {
        const data = this.viewDetails.info
        this.formData.template = data.template + '' || ''
        this.handleFeedbackTemplateChange(this.formData.template)
      }
    },

    handleFeedbackTemplateChange(v) {
      this.currItem = this.templateOptions.find((it) => it.key === v)
      this.$emit('on-template-change', { ...this.currItem, columns: this.feedbackTemplate_columns })
    },

    getColumns(columns) {
      if (!Array.isArray(columns)) return []
      const addWidth = ['1', '3'].includes(this.currItem.key)
      const r = [
        {
          title: '序号',
          align: 'center',
          width: 80,
          render: (h, params) => {
            return <div>{(this.formData.pageNo - 1) * 10 + params.index + 1}</div>
          },
        },
      ]
      for (let i = 0, len = columns.length; i < len; i++) {
        const _c = {
          title: columns[i].name,
          key: columns[i].field,
          align: 'center',
          ...columns[i],
        }
        /* 括号加宽度 */
        if (addWidth && /\(|（/.test(_c.title)) {
          const _m = _c.title.match(/\(|（/)
          /* 括号前面的数字大于4个的话 */
          if (_m.index > 4) {
            _c.width = 120
          } else {
            _c.width = 100
          }
        }
        r.push(_c)
      }
      return r
    },

    getParams() {
      return { template: this.formData.template }
    },

    templateOptionsDisable(status, fb, key) {
      const isContinue = typeof fb === 'function' ? fb() : fb
      this.templateOptions.forEach((it) => {
        let disabled = false
        if (it.key === key) {
          disabled = false
        } else if (isContinue && ['5', '6'].includes(it.key)) {
          disabled = false
        } else {
          disabled = status
        }
        it.disabled = disabled
        // debugger
      })
    },

    async getFeedbackTemplates() {
      const res = await getFeedbackTemplates()
      // console.log('getFeedbackTemplates', res)
      const data = res.data.data || []
      this.allTemplate = data
      this.templateOptions = this.allTemplate.map((it) => ({ disabled: false, ...it.name }))
    },
  },

  mounted() {
    // setTimeout(this.handleFormSubmit, 2000)
    this.getFeedbackTemplates()
  },
}
</script>

<style lang="less" scoped></style>
